package com.pig4cloud.pig.ads.controller.gdt;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

import com.pig4cloud.pig.api.util.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSON;
import com.pig4cloud.pig.api.gdt.dto.GdtTargetingTags;
import com.pig4cloud.pig.common.core.util.R;

import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;

/**
 * @广点通定向标签
 * @author zhuxm
 *
 */
@Log4j2
@RestController
@RequiredArgsConstructor
@RequestMapping("/gdtTargetingTags")
@Api(value = "/gdtTargetingTags", tags = "广点通定向标签")
public class GdtTargetingTagsController {

	private final StringRedisTemplate stringRedisTemplate;

	/**
	 * 获取广点通的请求地址
	 * https://developers.e.qq.com/oauth/authorize?client_id={0}&state={1}&scope={2}&account_type={3}&account_display_number={4}&redirect_uri={5}
	 */
	@GetMapping("/detail/{type}")
	public R tags(@PathVariable String type, @RequestParam(value="parentId" ,required =false ) String parentId){
		if(StringUtils.isBlank(type)) {
			return R.failed("参数配置错误");
		}

		String detail = stringRedisTemplate.opsForValue().get(Constants.GDT_TARGETING_TAGS_KEY_PRIX_ + type);
		if(StringUtils.isBlank(detail)) {		    
		    return R.ok();
		}
		//目前在此接口处理特殊数据。待稳定可放入定时任务提前处理好
		switch (type) {
			case "REGION" : //地域+商圈
				List<GdtTargetingTags> regionList = JSON.parseArray(detail, GdtTargetingTags.class);
				
				List<GdtTargetingTags> businessList = new ArrayList<>();
				
				detail = stringRedisTemplate.opsForValue().get(Constants.GDT_TARGETING_TAGS_KEY_PRIX_ + "BUSINESS_DISTRICT");
				if(StringUtils.isNotBlank(detail)) {					
					businessList = JSON.parseArray(detail, GdtTargetingTags.class);
					businessList.forEach(a ->{
						a.setBusiness(true);
					});
					regionList.addAll(businessList);
				}
				return R.ok(dealRegion(regionList));
//        	case "BUSINESS_DISTRICT" : //商圈
//        		List<GdtTargetingTags> businessList = JSON.parseArray(detail, GdtTargetingTags.class);
//        		return R.ok(dealBusiness(parentId, businessList));

			case "DEVICE_BRAND_MODEL":
				List<GdtTargetingTags> brandList = JSON.parseArray(detail, GdtTargetingTags.class);
				List<GdtTargetingTags> leveledData = dealLevels(brandList);
				return R.ok(leveledData);

			default :
				return R.ok();
		}

	}

	//处理区域逻辑
	private List<GdtTargetingTags> dealRegion(List<GdtTargetingTags> regionList) {

		//国外
		List<GdtTargetingTags> foreignList = new ArrayList<>();

		//国内
		List<GdtTargetingTags> ourList = new ArrayList<>();
		

		regionList.forEach(a -> {
			if(a.getId().compareTo(new BigInteger("9000"))==0){//国外
				foreignList.add(a);
			}
			if(a.getId().compareTo(new BigInteger("1156"))==0){//中国
				ourList.add(a);
			}
		});

		//获取国外
		digui(foreignList.stream().collect(Collectors.toCollection(TreeSet::new)), regionList); //调用递归算法查询市以下的区县

		//获取省市的层级关系
		digui(ourList.stream().collect(Collectors.toCollection(TreeSet::new)), regionList);

		ourList.addAll(foreignList);

		return ourList;
	}

	//处理商圈逻辑
	private List<GdtTargetingTags> dealBusiness(String parentId, List<GdtTargetingTags> businessList) {

		List<GdtTargetingTags> childList = new ArrayList<>();

		businessList.forEach(a -> {
			if(a.getParent_id().compareTo(new BigInteger(parentId))==0){//下级列表
				childList.add(a);
			}
		});

		//获取当前选项的所有下拉
		digui(childList.stream().collect(Collectors.toCollection(TreeSet::new)), businessList);

		return childList;
	}

	//递归获取自身及自身以下的节点
	private void digui(TreeSet<GdtTargetingTags> citys, List<GdtTargetingTags> regionList) {
		TreeSet<GdtTargetingTags> retList = new TreeSet<>();
		for (GdtTargetingTags tags : citys) {
			//获取自身子节点
			retList = regionList.stream().filter(re -> re.getParent_id().compareTo(tags.getId()) == 0).collect(Collectors.toCollection(TreeSet::new));
			if (retList.size() > 0) {
				tags.setChildren(retList);
				digui(retList, regionList); //循环调用自己
			}
		}
	}

	private List<GdtTargetingTags> dealLevels(List<GdtTargetingTags> arr){
		List<GdtTargetingTags> result = new ArrayList<>();

		arr.stream()
				.filter(item -> item.getParent_id().equals(BigInteger.valueOf(0)))
				.forEach(item -> {
					result.add(item);
					arr.stream()
							.filter(jtem -> jtem.getParent_id().equals(item.getId()))
							.forEach(jtem -> {
								item.getChildren().add(jtem);

								arr.stream()
										.filter(ktem -> ktem.getParent_id().equals(jtem.getId()))
										.forEach(ktem -> {
											jtem.getChildren().add(ktem);
										});
							});
				});


		return result;
	}
}
